#include <my_header.h>
#include <string.h>

/* Usage:  
 * 假设我们在test目录下有一个文件叫1.txt
 * 通过 open/read/write的函数
 * 把这个文件拷贝到另一个叫zs的文件夹内部
 * */

#define BUF_SIZE 4096
int copy_file(const char *src, const char *dst);

int main(void){                                  
    const char *src = "./test/1.txt";
    const char *dst = "./zs";
    
    int ret = copy_file(src, dst);
    if(ret == -1){
        return -1;
    }
    return 0;
}

int copy_file(const char *src, const char *dst_dir){
    // Make the dst path.
    char dst[1024];
    snprintf(dst, sizeof(dst), "%s/%s", dst_dir, "1.txt");

    // Open the src file.
    int src_fd = open(src, O_RDONLY);
    ERROR_CHECK(src_fd, -1, "open_src");

    // Open the dst file.
    int dst_fd = open(dst, O_WRONLY | O_CREAT | O_TRUNC, 0664);
    ERROR_CHECK(dst_fd, -1, "open_dst");

    // Copy file.
    char buf[BUF_SIZE] = {0};
    while(1){
        ssize_t read_count = read(src_fd, buf, sizeof(buf));
        if(read_count <= 0){
            break;
        }
        write(dst_fd, buf, read_count);
    }

    // Close file.
    close(src_fd);
    close(dst_fd);
    return 0;
}
